package com.cjm.one.security.aop;

import com.cjm.one.common.constant.SecurityConstants;
import com.cjm.one.common.exception.GlobalException;
import com.cjm.one.common.result.ResultCodeEnum;
import com.cjm.one.security.annotation.Within;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Aspect
@Component
public class SecurityWithinAspect implements Ordered {

    @Around("execution(* com.cjm.one..*.*(..)) && @annotation(within)")
    public Object around(ProceedingJoinPoint point, Within within) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String header = request.getHeader(SecurityConstants.FROM_SOURCE);
        log.info("开始校验权限header:{},within:{}", header,within.value());
        if (!(SecurityConstants.INNER.equals(header) && within.value())){

            throw new GlobalException(ResultCodeEnum.PERMISSION);
        }

        log.info("权限校验通过！！！！");
        return point.proceed();

    }

    @Override
    public int getOrder() {
        return  Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
